﻿
using Microsoft.EntityFrameworkCore.Metadata;
using Models.Common;
using Models.Device;
using Models.TaskPlain;
using NetTaste;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Drawing2D;
using System.IO.Ports;
using System.Text;
using System.Threading;
using static Models.Common.EnumDeviceState;
using GatewayServerService.Data;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using UtilsCache;
using Models.WebClient;
using GatewayServerService.CloudCenter;

namespace GatewayServerService.Device
{
    /// <summary>
    /// 中盛-脉冲计数器 8路
    /// </summary>
    public class ServiceDeviceRS4851026_MC8
    {
        ServiceCloudDeviceValueLog log = new ServiceCloudDeviceValueLog();
        //回调
        public void callBackUpdate(MQReqModel<object> httpReqModel)
        {
            //收到信息如：01 04 30 00 00 00 00 00 2F 00 00 00 00 00 3E 00 00 00 00 00 4C 00 00 00 00 00 7C 00 00 00 00 00 1A 00 00 00 00 00 12 00 00 00 00 00 0F 00 00 00 00 00 27 CF 89
            //158位
            try
            {
                ModelReceverData modelDeviceData = httpReqModel.toServerData;
                CommandLogModel commandLogModel = httpReqModel.toGatewayData;


                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
                ModelCommandAgreementParameter modelCommandAgreementParameter = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);
                if (modelDeviceData == null)
                {
                    return;
                }

                if (modelDeviceData.commandResults[0].value.Substring(0, 2) != commandLogModel.content.Substring(0, 2))
                {
                    return;
                }

                string result = modelDeviceData.commandResults[0].value;

                if (commandLogModel.key == "getCount" && !string.IsNullOrWhiteSpace(result))
                {

                    //-------------测试临时注释------------------
                    if (result.Length != 158)
                    {
                        //返回错误的结果
                        return;
                    }

                    string dataHex1 = result.Substring(15, 11);
                    string dataHex2 = result.Substring(33, 11);
                    string dataHex3 = result.Substring(51, 11);
                    string dataHex4 = result.Substring(69, 11);
                    string dataHex5 = result.Substring(87, 11);
                    string dataHex6 = result.Substring(105, 11);
                    string dataHex7 = result.Substring(123, 11);
                    string dataHex8 = result.Substring(141, 11);

                    if (result.Substring(9, 5) != "00 01" && result.Substring(9, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(27, 5) != "00 01" && result.Substring(27, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(45, 5) != "00 01" && result.Substring(45, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(63, 5) != "00 01" && result.Substring(63, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(81, 5) != "00 01" && result.Substring(81, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(99, 5) != "00 01" && result.Substring(99, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(117, 5) != "00 01" && result.Substring(117, 5) != "00 00")
                    {
                        return;
                    }
                    if (result.Substring(135, 5) != "00 01" && result.Substring(135, 5) != "00 00")
                    {
                        return;
                    }
                    //Console.WriteLine(result.Substring(27, 5));
                    //Console.WriteLine(result.Substring(45, 5));
                    //Console.WriteLine(result.Substring(63, 5));
                    //Console.WriteLine(result.Substring(87, 5));
                    //Console.WriteLine(result.Substring(99, 5));
                    //Console.WriteLine(result.Substring(117, 5));
                    //Console.WriteLine(result.Substring(135, 5));


                    int[] pulse = new int[9];
                    pulse[1] = new UtilsDataTypeChange().hex16Convert10(dataHex1);
                    pulse[2] = new UtilsDataTypeChange().hex16Convert10(dataHex2);
                    pulse[3] = new UtilsDataTypeChange().hex16Convert10(dataHex3);
                    pulse[4] = new UtilsDataTypeChange().hex16Convert10(dataHex4);
                    pulse[5] = new UtilsDataTypeChange().hex16Convert10(dataHex5);
                    pulse[6] = new UtilsDataTypeChange().hex16Convert10(dataHex6);
                    pulse[7] = new UtilsDataTypeChange().hex16Convert10(dataHex7);
                    pulse[8] = new UtilsDataTypeChange().hex16Convert10(dataHex8);



                    //查当次总流量 和历史总流量
                    double currentFlow = 0;
                    double totalFlow = 0;
                    int currentPulse = 0;
                    int totalPulse = 0;
                    int secondPulse = 0;
                    double secondflowSpeed = 0;
                    EFYihongIotContext ef = new EFYihongIotContext();
                    double deviceFactor = 0;//系数
                    double deviceCount = 0;//频率多少次一L
                                           //默认设置3.5MM口径
                    deviceFactor = 17.3;
                    deviceCount = 1038.0;

                    //查询8路设备，全部更新 
                    iot_device device = new DBIotDeviceCache().getClientDeviceByCache_60Min(commandLogModel.d_guid);
                    List<iot_device> modeldevicelist = UtilMemoryCacheHelper.get<List<iot_device>>("modeldevicelist" + device.d_model_guid);
                    if (modeldevicelist == null)
                    {
                        modeldevicelist = ef.iot_device.Where(c => c.d_model_guid == device.d_model_guid && c.d_gw_d_guid == device.d_gw_d_guid && c.d_status == 0).ToList();
                        UtilMemoryCacheHelper.set("modeldevicelist" + device.d_model_guid, modeldevicelist, 60);
                    }

                    for (int i = 1; i < 9; i++)
                    {
                        //if (i != 7)
                        //{
                        //   // continue;
                        //}
                        //if (i==7)
                        //{
                        //    int ii = 0;
                        //}

                        //避免重复处理
                        string plusecase = UtilMemoryCacheHelper.get<string>("pluse" + i);
                        if (!string.IsNullOrEmpty(plusecase) && plusecase == pulse[i].ToString())// && pulse[i] < 1
                        {
                            //数据重复，不操作,且为脉冲信号为0=不工作时
                            continue;
                        }
                        UtilMemoryCacheHelper.set("pluse" + i, pulse[i].ToString(), 60);
                        //------------------

                        List<iot_device> devices = modeldevicelist.Where(c => c.d_channel == i).ToList();
                        foreach (iot_device item in devices)
                        {
                            //判断流量计的口径型号规格



                            ModelCommandAgreement modelCommandAgreementDevice = JsonConvert.DeserializeObject<ModelCommandAgreement>(item.d_parameter);
                            ModelCommandAgreementParameter modelCommandAgreementParameterDevice = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreementDevice.agreementParameter);
                            if (modelCommandAgreementParameterDevice != null)
                            {
                                if (modelCommandAgreementParameterDevice.explain == "3.5mm")
                                {//3.5mm口径
                                    deviceFactor = 17.3;
                                    deviceCount = 1038.0;
                                }
                                else if (modelCommandAgreementParameterDevice.explain == "20mm")
                                {
                                    //20mm4分管口径
                                    deviceFactor = 7.5;
                                    deviceCount = 450.0;
                                }
                                else if (modelCommandAgreementParameterDevice.explain == "26mm")
                                {
                                    //26mm6分管口径
                                    deviceFactor = 6.5;
                                    deviceCount = 390.0;
                                }
                            }

                            //查当次总流量 和历史总流量
                            currentFlow = 0;
                            totalFlow = 0;
                            currentPulse = 0;
                            totalPulse = 0;
                            secondPulse = 0;
                            secondflowSpeed = 0;
                            //List<iot_device_value_current> list = ef.iot_device_value_current.Where(c => c.vc_d_guid == item.d_guid).ToList();
                            List<ViewDeviceCurrentValue> list = new DBIotDeviceValueCurrent().getViewDeviceCurrentValue(item.d_guid);
                            if (list.Count > 0)
                            {
                                int getfromCurrentPulse = int.Parse(list.Where(c => c.key == "currentPulse").FirstOrDefault().value);
                                if (getfromCurrentPulse == pulse[(int)item.d_channel])
                                {
                                    //流量计系统的值，跟取到的值相等==没有变化，退出
                                    continue;
                                }


                                currentPulse = pulse[i];
                                if (pulse[i] > 0)
                                {
                                    DateTime dt1 = list.Where(c => c.key == "currentPulse").FirstOrDefault().addtime;
                                    DateTime dt2 = DateTime.Now;
                                    TimeSpan ts = dt2 - dt1;

                                    secondPulse = pulse[(int)item.d_channel] - getfromCurrentPulse;
                                    if (ts.Seconds == 0)
                                    {
                                        continue;
                                    }
                                    if (secondPulse < 0)
                                    {//这里一定要，实现在停止时 secondPulse会为负数，计算总数totalPulse会出问题
                                        secondPulse = 0;
                                    }
                                    secondflowSpeed = secondPulse / ts.Seconds / deviceFactor;

                                }
                                int getData_totalPulse = int.Parse(list.Where(c => c.key == "totalPulse").FirstOrDefault().value);
                                totalPulse = getData_totalPulse + secondPulse;
                                currentFlow = pulse[i] / deviceCount;
                                totalFlow = totalPulse / deviceCount;


                            }
                            //else
                            //{
                            //    secondPulse = 0;
                            //    totalPulse = pulse[i];
                            //    currentFlow = currentPulse / deviceCount;
                            //    totalFlow = totalPulse / deviceCount;
                            //    secondflowSpeed = 0;

                            //}
                            //Console.WriteLine("currentPulse:" + currentPulse + "");
                            //Console.WriteLine("totalPulse:" + totalPulse + "");
                            //Console.WriteLine("currentFlow:" + currentFlow + "L");
                            //Console.WriteLine("totalFlow:" + secondflowSpeed + "L");

                            //如果每秒脉冲数，大于设备1L脉冲数，视为信息错误 不作处理
                            if (secondPulse > deviceCount * 10)
                            {
                                Console.WriteLine("脉冲数异常，丢弃secondPulse:" + secondPulse);
                                return;
                            }


                            //写日志
                            ServiceCloudDeviceValueLog log = new ServiceCloudDeviceValueLog();
                            log.writeSensorlog(item.d_guid, "secondPulse", secondPulse.ToString(), "每秒脉冲", result);
                            log.writeSensorlog(item.d_guid, "secondflowSpeed", UtilsNumber.GetNumberForLength(secondflowSpeed, 2).ToString(), "流速L/min", result);
                            log.writeSensorlog(item.d_guid, "currentPulse", currentPulse.ToString(), "当前脉冲", result);
                            log.writeSensorlog(item.d_guid, "currentFlow", UtilsNumber.GetNumberForLength(currentFlow, 2).ToString(), "当前流量L", result);
                            log.writeSensorlog(item.d_guid, "totalPulse", totalPulse.ToString(), "累计脉冲", result);
                            log.writeSensorlog(item.d_guid, "totalFlow", UtilsNumber.GetNumberForLength(totalFlow, 2).ToString(), "累计流量L", result);



                            Task.Run(() =>
                            {
                                //条件处理
                                new ServiceCloudLinkageCondition().linkageConditionAutoRun(item.d_guid);
                            });
                        }


                        //--------------------

                    }




                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

    }

}
